import moment from 'moment/moment';
import _ from 'lodash';
import { leftOptions } from './constant';
import { getCssVariableValue } from '@/utils/utils';

export const getTimesPoint = (time = moment().format('HH::ss')) => {
  if (time) {
    let hour = time.slice(0, 2);
    let min = time.slice(-2);
    return Number(hour) * 4 + Math.floor((min - 1) / 15) + 1;
  }
};

export const initTime = () => {
  return Array.from({ length: 96 }, (_, i) => {
    let num = (i + 1) * 15;
    num = Math.floor(num / 60) * 100 + (num % 60);
    num = ('' + num).padStart(4, '0');
    return {
      value: i + 1,
      label: num,
    };
  });
};

// 获取维度的默认的值
export const getDefaultAggregateValue = (leftValue = [], rightValue = []) => {
  const arr1 = leftValue.map((i) => i.value);
  const arr2 = rightValue.map((i) => i.value);
  return [arr1, arr2];
};

const buildColumn = () => {};

export const getHead = (arr = [], order = []) => {
  const column = [];
  if (!arr.length) {
    return column;
  }
  let title = order[0];
  title = leftOptions.find((i) => i.value === title);
  title = title?.label;
  column.push({
    lock: true,
    name: title,
    code: 'name',
    width: 160,
    align: 'center',
  });
  let index = 0;
  arr.forEach((i) => {
    const value = i.split('-');
    const length = value.length;
    if (length === 1) {
      value.forEach((v) => {
        column.push({
          name: v,
          code: 'value' + index,
          align: 'center',
          render: (v) => v || '-',
        });
        index++;
      });
    } else if (length === 2) {
      value.forEach((v, k) => {
        if (k === 0) {
          if (!column.some((s) => s.name === v)) {
            column.push({
              name: value[0],
              align: 'center',
              children: [],
            });
          }
        } else {
          column[column.findIndex((s) => s.name === value[0])].children.push({
            name: v,
            code: 'value' + index,
            align: 'center',
            render: (v) => v || '-',
          });
          index++;
        }
      });
    } else if (length === 3) {
      value.forEach((v, k) => {
        if (k === 0) {
          if (!column.some((s) => s.name === v)) {
            column.push({
              name: value[0],
              align: 'center',
              children: [],
            });
          }
        } else if (k === 1) {
          const children = column.find((f) => f.name === value[0])?.['children'] || [];
          if (!children.some((s) => s.name === v)) {
            column[column.findIndex((s) => s.name === value[0])].children.push({
              name: v,
              align: 'center',
              children: [],
            });
          }
        } else {
          column[column.findIndex((s) => s.name === value[0])].children[
            column[column.findIndex((s) => s.name === value[0])].children.findIndex(
              (s) => s.name === value[1],
            )
          ].children.push({
            name: v,
            code: 'value' + index,
            align: 'center',
            render: (v) => v || '-',
          });
          index++;
        }
      });
    }
  });
  return column;
};

const buildData = (data) => {
  const arr = [];
  const build = (d, arr) => {
    const keys = Object.keys(d);
    keys.forEach((i) => {
      if (i !== 'total') {
        const v = {};
        v['name'] = i || 0;
        let total = d[i] instanceof Array ? d[i] : d?.[i]?.['total'] || [];
        if (total.length !== 0) {
          total.forEach((f, k) => {
            v['value' + k] = f || 0;
          });
          v.children = [];
          arr.push(v);
          build(d[i], v['children']);
        }
      }
    });
  };
  build(data, arr);
  return arr;
};

const buildKey = (arr) => {
  const fun = (v, k = '') => {
    v?.forEach((a, b) => {
      a.key = k ? k + '-' + b : b + '';
      fun(a.children, a.key);
    });
  };
  fun(arr);
  return arr;
};

export const getData = (data = {}) => {
  let arr = [];
  if (!data || !data?.total?.length) {
    return arr;
  }
  if (data.total) {
    const obj = {
      name: '合计',
    };
    let total = data.total;
    total.forEach((i, k) => {
      obj['value' + k] = i || 0;
    });
    arr.push(obj);
    delete data.total;
  }
  arr = [...arr, ...buildData(data)];
  arr = buildKey(arr);
  return arr;
};

const getXData = (arr) => {
  const newArr = _.cloneDeep(arr);
  const value = [];
  const data = [];
  const fun = (v) => {
    v?.forEach((i) => {
      if (i.name !== '合计') {
        if (i?.children?.length) {
          fun(i.children);
        } else {
          value.push(i.name);
          delete i.name;
          delete i.key;
          delete i.children;
          data.push(Object.values(i));
        }
      }
    });
  };
  fun(newArr);
  return [value, data];
};

const findData = (f, d) => {
  let index = 0;
  let data = [];
  const fun = (arr) => {
    const value = f?.[index]?.['data'] || '';
    const obj = arr.filter((i) => i.name === value)?.[0] || {};
    if (obj?.children instanceof Array && index < f.length - 1) {
      index++;
      fun(obj.children);
    } else {
      arr?.forEach((e) => {
        data.push(e);
      });
    }
  };
  fun(d);
  return data;
};

const getSeries = (f, d, c, x, xd) => {
  let allKeys = [];
  if (f.length === 1) {
    const value = f?.[0]?.['value']?.map((i) => i.toString());
    const arr = [];
    c.forEach((i) => {
      if (value.some((s) => s === i.name)) {
        arr.push(i);
      }
    });
    allKeys = arr;
  } else if (f.length === 2) {
    const value = f?.[0]?.['value']?.map((i) => i.toString());
    const value2 = f?.[1]?.['value']?.map((i) => i.toString());
    let arr = [];
    c.forEach((i) => {
      if (value.some((s) => s === i.name)) {
        let children = i?.children || [];
        children = children.map((r) => ({ ...r, tag: i.name + '-' + r.name }));
        arr = [...arr, ...children];
      }
    });
    let arr2 = [];
    arr.forEach((i) => {
      if (value2.some((s) => s === i.name)) {
        arr2.push(i);
      }
    });
    allKeys = arr2;
  } else if (f.length === 3) {
    const value = f?.[0]?.['value']?.map((i) => i.toString());
    const value2 = f?.[1]?.['value']?.map((i) => i.toString());
    const value3 = f?.[2]?.['value']?.map((i) => i.toString());
    let arr = [];
    c.forEach((i) => {
      if (value.some((s) => s === i.name)) {
        let children = i?.children || [];
        children = children?.map((s) => ({ ...s, tag: i.name + '-' + s.name }));
        arr = [...arr, ...children];
      }
    });
    let arr2 = [];
    arr.forEach((i) => {
      if (value2.some((s) => s === i.name)) {
        let children = i?.children || [];
        children = children?.map((s) => ({ ...s, tag: i.tag + '-' + s.name }));
        arr2 = [...arr2, ...children];
      }
    });
    let arr3 = [];
    arr2.forEach((i) => {
      if (value3.some((s) => s === i.name)) {
        arr3.push(i);
      }
    });
    allKeys = arr3;
  }
  const series = [];
  allKeys.forEach((k, index) => {
    const arr = [];
    xd.forEach((i) => {
      arr.push(i[k.code] || null);
    });
    series.push({
      name: k.tag,
      data: arr,
      type: 'line',
    });
  });
  return series;
};

export const getChart = (filter, headFilter, data, columns) => {
  const xAxisData = findData(filter, data);
  let xAxis = xAxisData?.map((i) => i.name);
  let series = getSeries(headFilter, data, columns, xAxis, xAxisData);
  series = series || [];
  xAxis = xAxis || {};
  return {
    dataZoom: {
      type: 'slider',
      start: 0,
      end: 100,
      left: 40,
      right: 10,
      bottom: 20,
      height: 20,
      show: true,
      backgroundColor: getCssVariableValue('--bg-form'),
      dataBackground: {
        dataBackground: {
          areaStyle: { opacity: 0 },
          lineStyle: { opacity: 0 },
        },
      },
      selectedDataBackground: {
        areaStyle: {
          color: getCssVariableValue('--font-primary'),
          opacity: 0.15,
        },
        lineStyle: { color: 'transparent' },
      },
      borderColor: 'transparent',
      handleStyle: {
        color: getCssVariableValue('--bg-form'),
        borderColor: getCssVariableValue('--bd'),
      },
      brushSelect: false,
      showDetail: false,
    },
    grid: {
      bottom: 72,
      left: 48,
      right: 10,
      top: 12,
    },
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    tooltip: {},
    series,
    xAxis: [
      {
        data: xAxis,
        type: 'category',
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
    ],
  };
};

export const getChartFilterOptions = (left, data) => {
  const newData = _.cloneDeep(left);
  let index = 0;
  const fun = (a) => {
    const arr = [];
    let value = '';
    a?.forEach((i) => {
      if (i.name !== '合计') {
        arr.push({
          label: i.name,
          value: i.name,
        });
      }
    });
    value = newData[index]['data'] ? newData[index]['data'] : arr?.[0]?.['value'] || undefined;
    newData[index]['options'] = arr;
    newData[index]['data'] = value;
    const children = a.find((i) => i.name === value)?.['children'] || [];
    if (children?.length) {
      index++;
      fun(children);
    }
  };
  fun(data);
  return newData;
};

export const getChartHeadFilterOptions = (right, data) => {
  const arr = [];
  right?.forEach((i) => {
    const list = data?.[i.value]?.map((i) => ({ label: i, value: i })) || [];
    arr.push({
      ...i,
      list,
      value: list.map((i) => i.value),
    });
  });
  return arr;
};

const getStationValue = (arr, value) => {
  let data = '';
  arr?.forEach((i) => {
    i?.children?.forEach((f) => {
      if (f.label === value) {
        data = f.value;
      }
    });
  });
  return data;
};

export const getDeviationParams = (headFilter, filter, stations) => {
  let dataSource = headFilter?.find((i) => i.label === '数据源');
  dataSource = dataSource?.value || [];
  let date = filter?.find((i) => i.value === 'date');
  date = date?.data || '';
  const startDate = date;
  const endDate = date;
  let evaluationIndicator = headFilter?.find((i) => i.label === '模型');
  evaluationIndicator = evaluationIndicator?.value || [];
  let stationIds = filter?.find((i) => i.value === 'stationId');
  stationIds = stationIds?.data || '';
  stationIds = [getStationValue(stations, stationIds)];
  let version = headFilter?.find((i) => i.label === '版本');
  version = version?.value || [];
  return {
    dataSource,
    startDate,
    endDate,
    evaluationIndicator,
    stationIds,
    version,
  };
};

export const getDeviationQuantityChart = (data = {}) => {
  const xAxis = Object.keys(data);
  const series = [];
  xAxis?.forEach((i) => {
    const arr = Object.keys(data[i]);
    arr?.forEach((f) => {
      const obj = series.find((o) => o.name === f) || {
        type: 'line',
      };
      obj.name = f;
      obj.data = obj.data || [];
      const value = data[i][f];
      obj.data = [...obj.data, value];
      const index = series.findIndex((o) => o.name === f);
      if (index === -1) {
        series.push(obj);
      } else {
        series[index] = obj;
      }
    });
  });
  return {
    dataZoomSlider: true,
    grid: {
      bottom: 72,
      left: 48,
      right: 10,
      top: 12,
    },
    legend: {},
    tooltip: {},
    series,
    xAxis: [
      {
        data: xAxis,
        type: 'category',
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
  };
};

// 判断是否是当月之前
export const judgeIsBeforeMonth = (year, month) => {
  const dates = month?.map((i) => moment(`${year}-${i}-01`, 'YYYY-M-DD'));
  const currentDate = moment();
  return dates.some((i) => i <= currentDate);
};
